package start.demo01.erupt;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


public class CacheDemo {
	private Map<String,Object> cache = new HashMap<>();
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	public Object getData(String key) {//模拟从数据库加载数据对象
		//首先从缓存里根据key去拿取数据
		//读时上读锁
		rwl.readLock().lock();
		Object value = null;
		try {
			value = cache.get(key);
			if(value == null) {//如果缓存中没有该数据，从数据库中去加载,加载出后放进缓存
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				try {
					if(value == null) {
						value = "query db";
						cache.put(key, value);
					}
				}finally {
					rwl.writeLock().unlock();
				}
			}
		}finally {
			rwl.readLock().unlock();
		}
		return value;
	}
}
